<template>
  <basic-container>
    <avue-crud
      :option="options"
      v-model:search="search"
      v-model:page="page"
      v-model="form"
      :table-loading="loading"
      :data="data"
      :permission="permissionList"
      :before-open="beforeOpen"
      :before-close="beforeClose"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
      @tree-load="treeLoad"
    >
      <template #menu-left>
        <el-button
          type="danger"
          icon="el-icon-delete"
          plain
          v-if="permission.illness_delete"
          @click="handleDelete"
          >删 除
        </el-button>
        <!-- <el-button type="warning" plain icon="el-icon-download" @click="handleExport"
          >导 出
        </el-button> -->
      </template>
      <template #menu="scope">
        <el-button
          type="primary"
          text
          icon="el-icon-circle-plus"
          @click.stop="handleAdd(scope.row, scope.index)"
          >新增子项
        </el-button>
      </template>
    </avue-crud>
  </basic-container>
</template>

<script setup>
import {
  getList,
  getDetail,
  add,
  update,
  remove,
  getLazyList,
  getDeptTree,
} from '@/api/illness/illness';
import option from '@/option/illness/illness';
import { mapGetters } from 'vuex';
import { exportBlob } from '@/api/common';
import { getToken } from '@/utils/auth';
import { downloadXls } from '@/utils/util';
import { dateNow } from '@/utils/date';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import website from '@/config/website';
import { findObject } from '@smallwei/avue';
import { ref, reactive, computed, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter } from 'vue-router';
const router = useRouter();
const crud = ref(null);
const store = useStore();
const form = ref({});
const query = ref({});
const search = ref({});
let loading = ref(false);
const page = ref({
  pageSize: 10,
  currentPage: 1,
  total: 0,
});
const selectionList = ref([]);
const options = ref(option);
const data = ref([]);
const parentId = ref(0);
// permissionList 计算属性
const permission = computed(() => store.getters.permission);
const validData = (value, defaultVal = false) => (value ? true : defaultVal);
const permissionList = computed(() => ({
  addBtn: validData(permission.value.illness_add, false),
  viewBtn: validData(permission.value.illness_view, false),
  delBtn: validData(permission.value.illness_delete, false),
  editBtn: validData(permission.value.illness_edit, false),
}));

// ids 计算属性
const ids = computed(() => {
  return selectionList.value.map(ele => ele.id).join(',');
});
const initData = tenantId => {
  getDeptTree(tenantId).then(res => {
    const column = findObject(options.value.column, 'parentId');
    column.dicData = res.data.data;
  });
};
const handleAdd = (row, index) => {
  parentId.value = row.id;
  const column = findObject(options.value.column, 'parentId');
  column.value = row.id;
  column.addDisabled = true;
  crud.value.rowAdd();
};
const rowSave = (row, done, loading) => {
  row.hasChildren = true;
  add(row)
    .then(() => {
      parentId.value = 0;
      onLoad(page.value);
      ElMessage.success('操作成功!');
      done();
    })
    .catch(error => {
      loading();
      console.log(error);
    });
};

const rowUpdate = (row, index, done, loading) => {
  update(row)
    .then(() => {
      onLoad(page.value);
      ElMessage.success('操作成功!');
      done();
    })
    .catch(error => {
      loading();
      console.log(error);
    });
};

const rowDel = row => {
  ElMessageBox.confirm('确定将选择数据删除?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      return remove(row.id);
    })
    .then(() => {
      onLoad(page.value);
      ElMessage.success('操作成功!');
    });
};

const handleDelete = () => {
  if (selectionList.value.length === 0) {
    ElMessage.warning('请选择至少一条数据');
    return;
  }
  ElMessageBox.confirm('确定将选择数据删除?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      return remove(ids.value);
    })
    .then(() => {
      onLoad(page.value);
      ElMessage.success('操作成功!');
    });
};

const handleExport = () => {
  const downloadUrl = `/blade-illness/illness/export-illness?${website.tokenHeader}=${getToken()}`;
  const { name } = this.query;
  let values = {
    name_: name,
  };

  ElMessageBox.confirm('是否导出数据?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    NProgress.start();
    exportBlob(downloadUrl, values).then(res => {
      downloadXls(res.data, `疾病管理${dateNow()}.xlsx`);
      NProgress.done();
    });
  });
};

const beforeOpen = (done, type) => {
  if (['add', 'edit'].includes(type)) {
    initData(form.value.tenantId);
  }
  if (['edit', 'view'].includes(type)) {
    getDetail(form.value.id).then(res => {
      form.value = Object.assign(res.data.data, {
        hasChildren: form.value.hasChildren,
      });
    });
  }
  done();
};

const beforeClose = done => {
  parentId.value = '';
  const column = findObject(options.value.column, 'parentId');
  column.value = '';
  column.addDisabled = false;
  done();
};

const searchReset = () => {
  query.value = {};
  onLoad(page.value);
};

const searchChange = (params, done) => {
  query.value = params;
  page.value.currentPage = 1;
  onLoad(page.value, params);
  done();
};

const selectionChange = list => {
  selectionList.value = list;
};

const selectionClear = () => {
  selectionList.value = [];
  crud.value.toggleSelection();
};

const currentChange = currentPage => {
  page.value.currentPage = currentPage;
};

const sizeChange = pageSize => {
  page.value.pageSize = pageSize;
};

const refreshChange = () => {
  onLoad(page.value, query.value);
};

const onLoad = (page, params = {}) => {
  loading.value = true;

  const values = { ...query.value };

  getLazyList(parentId.value, values).then(res => {
    const DATA = res.data.data;
    page.total = DATA.total;
    data.value = DATA;
    // data.value[0].hasChildren = true;
    loading.value = false;
    selectionClear();
  });
};
const treeLoad = (tree, treeNode, resolve) => {
  const parentId = tree.id;
  getLazyList(parentId).then(res => {
    resolve(res.data.data);
  });
};
</script>

<style>
</style>
